import React, { useEffect } from 'react';
import { Form, Input, Modal, message } from 'antd';
import { createSchool, updateSchool } from '@/services/school';

interface SchoolFormProps {
  visible: boolean;
  values?: API.School;
  onCancel: () => void;
  onSuccess: () => void;
}

const SchoolForm: React.FC<SchoolFormProps> = ({
  visible,
  values,
  onCancel,
  onSuccess,
}) => {
  const [form] = Form.useForm();
  const isUpdate = !!values; // 是否为更新操作

  // 当values变化时，重置表单
  useEffect(() => {
    if (values) {
      form.setFieldsValue(values);
    } else {
      form.resetFields();
    }
  }, [form, values]);

  // 关闭弹窗时重置表单
  const handleCancel = () => {
    form.resetFields();
    onCancel();
  };

  // 提交表单
  const handleSubmit = async () => {
    try {
      const fieldsValue = await form.validateFields();
      const hide = message.loading(`正在${isUpdate ? '更新' : '创建'}...`);

      try {
        if (isUpdate && values) {
          await updateSchool(values.id, fieldsValue);
        } else {
          await createSchool(fieldsValue);
        }
        hide();
        message.success(`${isUpdate ? '更新' : '创建'}成功`);
        onSuccess();
      } catch (error) {
        hide();
        message.error(`${isUpdate ? '更新' : '创建'}失败，请重试!`);
      }
    } catch (error) {
      console.log('校验失败:', error);
    }
  };

  return (
    <Modal
      title={isUpdate ? '编辑学校' : '新增学校'}
      open={visible}
      onOk={handleSubmit}
      onCancel={handleCancel}
      destroyOnClose
    >
      <Form
        form={form}
        labelCol={{ span: 5 }}
        wrapperCol={{ span: 18 }}
        layout="horizontal"
      >
        <Form.Item
          name="name"
          label="学校名称"
          rules={[{ required: true, message: '请输入学校名称' }]}
        >
          <Input placeholder="请输入学校名称" />
        </Form.Item>

        <Form.Item
          name="groupName"
          label="所属集团"
          rules={[{ required: true, message: '请输入所属集团' }]}
        >
          <Input placeholder="请输入所属集团" />
        </Form.Item>

        <Form.Item
          name="address"
          label="学校地址"
          rules={[{ required: true, message: '请输入学校地址' }]}
        >
          <Input placeholder="请输入学校地址" />
        </Form.Item>

        {isUpdate ? (
          <Form.Item
            name="website"
            label="网站地址"
            rules={[{ type: 'url', message: '请输入正确的网站地址' }]}
          >
            <Input placeholder="请输入网站地址" />
          </Form.Item>
        ) : (
          <Form.Item
            name="regionName"
            label="所属区域"
            rules={[{ required: true, message: '请输入所属区域' }]}
          >
            <Input placeholder="请输入所属区域" />
          </Form.Item>
        )}
      </Form>
    </Modal>
  );
};

export default SchoolForm;
